package com.leo.cloud.common.utils.docks;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.leo.cloud.common.utils.Constant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 文件名：Word2PDF.java
 *
 * @create 2021-03-25 10:09
 * <p>
 */
public class Word2PDF {
//    private static Logger logger = LoggerFactory.getLogger("--word转pdf--");
    public static void main(String[] args) throws Exception{
        String resourcesDir = "E:\\";
        String wordPath = resourcesDir+"test.doc";
        String wordChangePdf = wordChangePdf(wordPath);
//        logger.info(wordChangePdf);
    }
    /**
     * wordPath 需要被转换的word全路径带文件名
     */
    public static String wordChangePdf(String wordPath) throws Exception{
        long old = System.currentTimeMillis();
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return "";
        }
        String pdfPath = wordPath.substring(0, wordPath.lastIndexOf("."))+old+".pdf";
        File file = new File(pdfPath); // 新建一个pdf文档
        FileOutputStream os = new FileOutputStream(file);
        Document doc = new Document(wordPath); // Address是将要被转化的word文档
        // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
        doc.save(os, com.aspose.words.SaveFormat.PDF);
        long now = System.currentTimeMillis();
        os.close();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
        return pdfPath;
    }

    private static boolean getLicense() {
        boolean result = false;
        try {
            // 哪里用license.xml
            InputStream is = new FileInputStream(Constant.fileRootpath+"docs"+File.separator+"License.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
